package com.zzb.weixin.servlet;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zzb.util.StringUtil;
import com.zzb.weixin.WeiXinService;
import com.zzb.weixin.constant.WXUrlName;
import com.zzb.weixin.exception.WeiXinException;
import com.zzb.weixin.json.JsonObject;

/**
 * 处理微信服务器请求的Servlet URL地址：http://xxx/signature
 * 
 * 注意：官方文档限制使用80端口哦！
 * 
 */
public class WinXinJSServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	/**
	 * 处理微信服务器验证
	 * 
	 */
	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		try {
			String url = request.getParameter(WXUrlName.URL);// 随机字符串
			if(url != null && url.indexOf("#")>0){
				url = url.substring(0,url.indexOf("#"));
			}
			String jsapiTicket = WeiXinService.getJsAPIToken().getAccessToken();
			String nonce = StringUtil.getRandomStr();
			String timestamp = System.currentTimeMillis()+"";
			String Signature = WeiXinService.creatJsSignature(timestamp, nonce, jsapiTicket, url.toString());
			
			JsonObject jo = new JsonObject();
			jo.put("appid",WeiXinService.getAppId());
			jo.put("url",url.toString());
			jo.put("nonce",nonce);
			jo.put("timestamp",timestamp);
			jo.put("Signature",Signature);
			
			Writer out = response.getWriter();
			response.setContentType("text/json; charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");
			String callback = request.getParameter("callback");
			if (!StringUtil.isEmpty(callback)) {
				out.write(callback+"("+jo.toString()+")");
			}else{
				out.write(jo.toString());
			}
			out.flush();
			out.close();
		} catch (WeiXinException e) {
			e.printStackTrace();
		}
	}
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}
}
